using System.Collections.Generic;
using Headspring.Training.Domain;
using Headspring.Training.Domain.Model;
using Headspring.Training.Domain.Services;
using NHibernate;
using NHibernate.Expression;
using StructureMap;

namespace Headspring.Training.DataAccess.Impl
{
	[Pluggable(Keys.DEFAULT)]
	public class WorkOrderRepository : RepositoryBase, IWorkOrderRepository
	{
		public void Save(WorkOrder workOrder)
		{
			ISession session = getSession();
			ITransaction transaction = session.BeginTransaction();
			session.SaveOrUpdate(workOrder);
			transaction.Commit();
		}

		public WorkOrder GetWorkOrder(string number)
		{
			ISession session = getSession();
			ICriteria criteria = session.CreateCriteria(typeof(WorkOrder));
			criteria.Add(Expression.Eq("Number", number));
			WorkOrder result = criteria.UniqueResult<WorkOrder>();
			return result;
		}

		public WorkOrder[] GetWorkOrders(WorkOrderSearchSpecification specification)
		{
			ISession session = getSession();
			ICriteria criteria = session.CreateCriteria(typeof(WorkOrder));

			if (specification.Assignee != null)
			{
				criteria.Add(Expression.Eq("Assignee", specification.Assignee));
			}

			if(specification.Creator != null)
			{
				criteria.Add(Expression.Eq("Creator", specification.Creator));
			}

			if(specification.Status != null)
			{
				criteria.Add(Expression.Eq("Status", specification.Status));
			}

			IList<WorkOrder> list = criteria.List<WorkOrder>();
			return new List<WorkOrder>(list).ToArray();
		}
	}
}